package casa.depesos.app.com.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.google.gson.JsonParser;

import java.util.HashMap;

import casa.depesos.app.com.App;
import casa.depesos.app.com.BuildConfig;
import casa.depesos.app.com.databinding.ActivityWebBinding;
import casa.depesos.app.com.utils.Constant;
import casa.depesos.app.com.utils.Utils;

public class WebActivity extends BaseActivity {

    ActivityWebBinding binding;

    @Override
    protected boolean isBlack() {
        return false;
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        binding = ActivityWebBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        if (getIntent().hasExtra("title")) {
            String s = getIntent().getStringExtra("title");
            if (!TextUtils.isEmpty(s)) {
                binding.top.title.setText(s);
            }
        }
        binding.top.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goBack();
            }
        });
//        if (getIntent().getBooleanExtra("top", false)) {
//            binding.top.setVisibility(View.VISIBLE);
//        }
        WebSettings settings = binding.web.getSettings();
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setDomStorageEnabled(true);//是否支持 Local Storage
        settings.setJavaScriptEnabled(true);//支持JavaScript
        settings.setUseWideViewPort(true);//使Webview具有普通的视口(例如普通的桌面浏览器)
        settings.setLoadWithOverviewMode(true);//加载完全缩小的WebView

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setMediaPlaybackRequiresUserGesture(false);
        }

        binding.web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    binding.progress.setVisibility(View.GONE);
                } else {
                    binding.progress.setVisibility(View.VISIBLE);
                    binding.progress.setProgress(newProgress);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                binding.top.title.setText(title);
            }
        });
        binding.web.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                String scheme = uri.getScheme();
                if (scheme.equals("http") || scheme.equals("https")) {
                    return false;
                } else {
                    toSysWeb(uri);
                    return true;
                }
            }
        });

        binding.web.addJavascriptInterface(new Js(), "casadepesos");
        String url = getIntent().getStringExtra("url");
        binding.web.loadUrl(url);
    }

    public static void launch(Context c, String url) {
        Intent i = new Intent(c, WebActivity.class);
        i.putExtra("url", url);
        if (c instanceof Activity == false) {
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        c.startActivity(i);
    }

    public static void startGooglePlay(String link) {
        try {
            if (WebActivity.toSysWeb(link)) {
                return;
            }
            Intent tempIntent =
                    new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + BuildConfig.APPLICATION_ID));
            tempIntent.setPackage("com.android.vending");
            if (tempIntent.resolveActivity(App.getApp().getPackageManager()) == null) {
                String appAddress = "https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID;
                tempIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(appAddress));
            }
            tempIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            App.getApp().startActivity(tempIntent);
        } catch (Throwable e) {
            Log.e("debug_Launch", "skipAppStore Launch 290 error = " + e.getMessage());
        }
    }

    public static boolean toSysWeb(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        return toSysWeb(Uri.parse(url));
    }

    public static boolean toSysWeb(Uri uri) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            App.getApp().startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void goBack() {
        if (binding.web.canGoBack()) {
            binding.web.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        Utils.freeWeb(binding.web);
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        binding.web.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        binding.web.onResume();
    }

    class Js {

        @JavascriptInterface
        public String queryAndroidMethods(String type, String json) {
            if ("11".equals(type)) {
                if (!TextUtils.isEmpty(Utils.getToken())) {
                    finish();
                    return "";
                }
                h.post(() -> {
                    Intent i = new Intent(WebActivity.this, LoginActivity.class);
                    startActivity(i);
                    finish();
                });
            } else if ("12".equals(type)) {
                h.post(() -> {
                    int i = JsonParser.parseString(json.toString()).getAsJsonObject().get("type").getAsInt();
                    if (i == 0) {
                        hideLoading();
                    } else if (i == 1) {
                        showLoading(false);
                    }
                });
            } else if ("13".equals(type)) {//report, todo

            }
            return "";
        }

        @JavascriptInterface
        public String queryAndroidMessage(int type) {
            try {
                HashMap obj = new HashMap();
                obj.put("appVersion", BuildConfig.VERSION_CODE);
                obj.put("applyId", Constant.getApplyId());
                obj.put("mobeneToken", Constant.getToken());
                obj.put("token", Utils.getToken());
                obj.put("userId", Utils.getUid());
                obj.put("packageName", BuildConfig.APPLICATION_ID);
                obj.put("appversionName", BuildConfig.VERSION_NAME);
                obj.put("mobile", Utils.getPhone());
                obj.put("isWhiteUser", Constant.white);

                obj.put("adid", Constant.adid);
                obj.put("gpsAdid", Constant.gpsAdid);
                obj.put("adjustGpsAdid", Constant.adjustGpsAdid);
                obj.put("instanceId", Constant.instanceId);

                return new Gson().toJson(obj);
            } catch (Throwable e) {
                e.printStackTrace();
                return "{}";
            }
        }
    }
}
